package indi.kider.server.apartment.service;

import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import indi.kider.common.constant.*;
import indi.kider.common.model.apabus.Rent;
import indi.kider.common.model.apabus.RentOutline;
import indi.kider.common.model.apartment.Community;
import indi.kider.common.model.apartment.Houses;
import indi.kider.common.model.apartment.HousesMsg;
import indi.kider.common.model.employee.Employee;
import indi.kider.common.model.employee.Tenant;
import indi.kider.common.model.employee.TenantQuery;
import indi.kider.common.model.query;
import indi.kider.server.apabus.mapper.RentMapper;
import indi.kider.server.apabus.mapper.RentOutlineMapper;
import indi.kider.server.apartment.mapper.CommunityMapper;
import indi.kider.server.apartment.mapper.HousesMapper;
import indi.kider.server.apartment.model.*;
import indi.kider.server.apartment.service.related.ApabusService;
import indi.kider.server.apartment.service.related.EmployeeService;
import indi.kider.server.apartment.util.BuildModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import pers.vankid.common.model.base.CoreException;
import pers.vankid.common.utils.page.PageRequest;
import pers.vankid.common.utils.page.PageResponse;
import pers.vankid.common.utils.page.PageUtil;
import tk.mybatis.mapper.entity.Example;

import java.util.*;

@Service
public class ApartmentServiceImpl implements ApartmentService {

    @Autowired
    private CommunityMapper communityMapper;

    @Autowired
    private HousesMapper housesMapper;

    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private RentOutlineMapper rentOutlineMapper;
    @Autowired
    private RentMapper rentMapper;


    @Override
    public List<City> queryCityByUserCode(Long enterpriseId) {
        List<Community> list = communityMapper.selectAllGroupByCity(enterpriseId);
        Map<String, List<City>> area = new HashMap<>();
        for (Community community : list) {
            String cityName = community.getCity();
            String areaName = community.getArea();

            List<City> templist = area.get(cityName);
            if (templist == null) {
                templist = Lists.newArrayList();
            }
            templist.add(new City(areaName));
            area.put(cityName, templist);
        }

        List<City> cities = Lists.newArrayList();
        for (String cityName : area.keySet()) {
            City tc = new City(cityName);
            tc.setChildren(area.get(cityName));
            cities.add(tc);
        }

        return cities;
    }

    @Override
    public HousesMsg queryHouseById(Long housesId) {
        Rent query = new Rent();
        query.setHousesId(housesId);
        query.setState(RentStateCons.VALID);
        Rent rent = rentMapper.selectOne(query);
        HousesMsg msg = housesMapper.selectHouseMsgByHousesId(housesId);
        msg.setRent(rent);
        return msg;
    }

    @Override
    public Community queryCommunityById(Long id) {
        return communityMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Community> queryCommunityByArea(String cityName, String area, Long enterpriseId) {
        Community community = new Community();
        community.setCity(cityName);
        community.setArea(area);
        community.setEnterpriseId(enterpriseId);
        List<Community> communitys = communityMapper.select(community);
        communitys.stream().forEach(community1 -> {
            community1.setSize(housesMapper.selectCommunityHousesSize(community1.getId()));
            TenantQuery tenantQuery=new TenantQuery();
            tenantQuery.setCommunityId(community1.getId());
            community1.setTenantSizeAll(communityMapper.getTenantSizeByCommunity(tenantQuery));
            tenantQuery.setState(StatusCons.VALID);
            community1.setTenantSizeNow(communityMapper.getTenantSizeByCommunity(tenantQuery));
                }
        );
        return communitys;
    }

    @Override
    public int updateCommunity(Community community) {
        return communityMapper.updateByPrimaryKeySelective(community);
    }

    @Override
    public int addCommunity(Community community) {
        return communityMapper.insertSelective(community);
    }

    @Override
    public Houses addHouse(Houses houses) {
        if (houses.getState() == null)
            houses.setState(HouseStateCons.VACANCY);
        housesMapper.insertSelective(houses);
        return houses;
    }

    @Override
    public RentOutline addHouse(Houses houses, Employee employee) {
        Houses inHouses = this.addHouse(houses);
        RentOutline rentOutline = new RentOutline();
        rentOutline.setState(RentOutlineStateCons.VACANCY);
        rentOutline.setEmployeeId(employee.getId());
        rentOutline.setEnterprise(Long.valueOf(employee.getEnterpriseId()));
        rentOutline.setHousesId(inHouses.getId());
        rentOutline.setRentTime(new Date());
        rentOutline.setRemark("自动");
        rentOutlineMapper.insertSelective(rentOutline);
        return rentOutline;
    }

    @Override
    public int updateHouse(Houses houses) {
        Houses houses1 = housesMapper.selectByPrimaryKey(houses.getId());
        if (houses1.getState() ==2 ) {
            return -2;
        }
        houses.setState(null);
        return housesMapper.updateByPrimaryKeySelective(houses);
    }

    /**
     * 更新房屋状态
     *
     * @param houses
     */
    @Override
    public void updateHouseState(Houses houses) {
        housesMapper.updateByPrimaryKeySelective(houses);
    }

    @Override
    public List<Houses> queryByArea(String community) {
        Community cy = new Community();
        cy.setCommunity(community);
        Community tempc = communityMapper.selectOne(cy);
        return queryByArea(tempc.getId());
    }


    @Override
    public List<Houses> queryByArea(Long communityId) {
        Houses houses = new Houses();
        houses.setCommunityId(communityId);
        return housesMapper.select(houses);
    }

    @Override
    public void delCommunityById(Long communityId) throws CoreException {
        if (!this.hasHousesOfThisCommunity(communityId)) {
            communityMapper.deleteByPrimaryKey(communityId);
        } else throw new CoreException("当前小区下存在房屋，请先删除房屋！");
    }

    @Override
    public void delHouseById(Long houseId) throws CoreException {
        int candel = this.hasBusOfThisHouse(houseId);
        if ( candel == 0) {
            housesMapper.deleteByPrimaryKey(houseId);

        } else {
            String waring = candel > 1 ? "当前房屋已经表具设备，不允许删除！" : "当前房屋已被使用，不允许删除！";
            throw new CoreException(waring);
        }
    }

    @Override
    public boolean hasBusOfThisCommunity(Long communityId) {
        Integer count = communityMapper.selectCommunityHasUsed(communityId);
        return count > 0 ? true : false;
    }

    @Override
    public boolean hasHousesOfThisCommunity(Long communityId) {
        Integer count = communityMapper.selectCommunityHasHouses(communityId);
        return count > 0 ? true : false;
    }

    @Override
    public int hasBusOfThisHouse(Long houseId) {
        Integer count = housesMapper.selectHouseIdHasUsed(houseId);
        if(count > 0){
            return 1;
        }else {
            Integer meters = housesMapper.selectHouseIdHasUsedMeter(houseId);
            return meters > 0 ? 2 : 0;
        }
    }

    /**
     * 获取社区标题
     *
     * @param request
     * @return
     */
    @Override
    public PageResponse<CommunityTitle> getCommunityTitleList(PageRequest<HousesCommunityQuery> request) {
        PageUtil.start(request);
        List<CommunityTitle> communityTitles = communityMapper.getCommunityTitleList(request.getQuery());
        //
        PageResponse<CommunityTitle> pageResponse = PageUtil.getPageResponse(communityTitles);
        if (communityTitles.size() == 1 && (communityTitles.get(0) == null || communityTitles.get(0).getCommunityId() == null)) {
            pageResponse.setRows(null);
            pageResponse.setTotal(0L);
            pageResponse.setSize(0L);
        } else {
            HousesCommunityQuery query = request.getQuery();
            communityTitles.stream().forEach(communityTitle -> {
                query.setCommunityId(communityTitle.getCommunityId());
                List<Houses> voList = housesMapper.getHouseRentList(query);
                List<HouseRent> houseRentList = new ArrayList<>();
                voList.stream().forEach(vo -> {
                    HouseRent houseRent = BuildModel.buildHouseRentsByHouse(vo);
                    houseRent.setCommunity(communityTitle.getCommunity());
                    houseRentList.add(houseRent);
                });
                communityTitle.setRoomList(houseRentList);
                communityTitle.setCount(houseRentList.size());
            });
        }
        return pageResponse;
    }

    /**
     * 获取房源列表
     * @param request
     * @return
     */
    public PageResponse<CommunityTitle> getCommunityListNew(PageRequest<HousesCommunityQuery> request) {
        PageUtil.start(request);
        HousesCommunityQuery query = request.getQuery();
        PageUtil.start(request);
        List<Houses> voList = housesMapper.getHouseRentList(query);
        PageResponse<Houses> pageResponse = PageUtil.getPageResponse(voList);
        List<HouseRent> houseRentList = new ArrayList<>();
        voList.stream().forEach(vo -> {
            HouseRent houseRent = BuildModel.buildHouseRentsByHouse(vo);
            houseRentList.add(houseRent);
        });
        List<CommunityTitle> communityTitles = new ArrayList<>();
        CommunityTitle c = new CommunityTitle();
        c.setOpen(true);
        c.setRoomList(houseRentList);
        communityTitles.add(c);
        PageResponse<CommunityTitle> re = new PageResponse(communityTitles, pageResponse.getTotal(),pageResponse.getSize());
        return re;
    }


    /**
     * 获取房屋标题
     *
     * @param request
     * @return
     */
    @Override
    public PageResponse<HouseRent> getHouseRentList(PageRequest<HousesCommunityQuery> request) {
        PageUtil.start(request);
        List<Houses> voList = housesMapper.getHouseRentList(request.getQuery());
        List<HouseRent> houseRents = new ArrayList<>();
        voList.stream().forEach(vo -> houseRents.add(BuildModel.buildHouseRentsByHouse(vo)));
        return PageUtil.getPageResponse(houseRents);
    }

    @Override
    public PageResponse<List<HousesMsg>> selectHouseMsgByEnterprise(PageRequest<String> request) {
        PageUtil.start(request);
        List<HousesMsg> list = housesMapper.selectHouseMsgByEnterprise(request.getQuery());
        list.stream().forEach(housesMsg -> {
            if (housesMsg.getFriendsSize() != null && housesMsg.getFriendsSize() > 0) {
                List<Tenant> friends = employeeService.getTenants(housesMsg.getTenantId()).getData();
                housesMsg.setFriends(friends);
            }
            if (housesMsg.getState().equals(HouseStateCons.RENTED)) {
                Rent query = new Rent();
                query.setHousesId(housesMsg.getId());
                query.setState(RentStateCons.VALID);
                Rent rent = rentMapper.selectOne(query);
                housesMsg.setRent(rent);
            }
        });
        return PageUtil.getPageResponse(list);
    }


    @Override
    public List<String> verifyTheDeviceIsUsed(List<String> meters, Integer meterType) {
        return housesMapper.verifyTheDeviceIsUsed(meterType, meters);
    }

    public HouseRent addDefHouses(Long communitId, Long id, Employee employee) {
        // 生成默认门牌
        Houses houses = new Houses();
        houses.setCommunityId(communitId);
        int count = housesMapper.selectCount(houses);
        String houseNumb = "WN_" + Strings.padStart(String.valueOf(count), 4, '0');
        // 取模板
        if (id == null) {
            id = 1L;
        }
        houses = housesMapper.selectByPrimaryKey(id);
        // 修改模板再插入.
        houses.setCommunityId(communitId);
        houses.setHouseNumb(houseNumb);
        houses.setId(null);
        houses.setState(1);//状态空闲
        houses.setWaterMeter(null);
        houses.setPowerMeter(null);
        houses.setReleaseState(HouseReserveCons.NO_RESRVE); // 原来已经发布的房源直接变成未发布状态
        houses.setInSumCnt(0);
        houses.setInManCnt(0);
        houses.setInFemanCnt(0);
        housesMapper.insertSelective(houses);
        // 关系=============================
        RentOutline rentOutline = new RentOutline();
        rentOutline.setState(RentOutlineStateCons.VACANCY);
        rentOutline.setEmployeeId(employee.getId());
        rentOutline.setEnterprise(Long.valueOf(employee.getEnterpriseId()));
        rentOutline.setHousesId(houses.getId());
        rentOutline.setRentTime(new Date());
        rentOutline.setRemark("自动");
        rentOutlineMapper.insertSelective(rentOutline);
        // 关系=============================
        return BuildModel.buildHouseRentsByHouse(houses);
    }


    @Override
    public int checkNameAndNumber(Community community) {
        Example example = new Example(Community.class);
        example.createCriteria().orEqualTo("communityCode", community.getCommunityCode())
                .orEqualTo("community", community.getCommunity());
        List<Community> list = communityMapper.selectByExample(example);
        if(null == list || list.isEmpty()){
            return 0;
        } else {
            Community community1 = list.get(0);
            if (community1.getCommunity().equals(community.getCommunity()))
                return 1;
            if (community1.getCommunityCode().equals(community.getCommunityCode()))
                return 2;
        }
        return 0;
    }
}
